package com.ChengXiZi.service.impl;

import com.ChengXiZi.constant.MessageConstant;
import com.ChengXiZi.constant.StatusConstant;
import com.ChengXiZi.dto.UserAddDTO;
import com.ChengXiZi.dto.UserLoginDto;
import com.ChengXiZi.dto.UserPageDTO;
import com.ChengXiZi.exception.AccountLockedException;
import com.ChengXiZi.exception.AccountNotAllowedException;
import com.ChengXiZi.exception.AccountNotFoundException;
import com.ChengXiZi.entity.User;
import com.ChengXiZi.exception.PasswordErrorException;
import com.ChengXiZi.mapper.UserMapper;
import com.ChengXiZi.result.PageResult;
import com.ChengXiZi.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;


@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 普通用户登录
     * @param userLoginDto
     * @return
     */
    @Override
    public User login(UserLoginDto userLoginDto) {
        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword();

        //1、根据用户名查询数据库中的数据
        User user = userMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        if(user.getIdentity() == 2) {
            //账号类型不允许
            throw new AccountNotAllowedException(MessageConstant.ACCOUNT_NOT_ALLOWED);
        }

        //对密码进行MD5加密，而后进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        if (user.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return user;
    }

    /**
     * 创建用户
     * @param userAddDTO
     * @return
     */
    @Override
    public void save(UserAddDTO userAddDTO) {
        //对象属性拷贝
        User user = new User();
        BeanUtils.copyProperties(userAddDTO,user);

        //给密码进行MD5加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        //给user赋值创建时间
        user.setCreateTime(LocalDateTime.now());

        userMapper.insert(user);
    }

    /**
     * 查询用户
     * @param userPageDTO
     * @return
     */
    @Override
    public PageResult pageQuery(UserPageDTO userPageDTO) {
        PageHelper.startPage(userPageDTO.getPage(),userPageDTO.getPageSize());
        Page<User> page = userMapper.pageQuery(userPageDTO);

        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 社区管理员封禁普通用户账号
     * @param status
     * @param targetid
     * @param userId
     * @return
     */
    @Override
    public void startOrStop(Integer status, Long targetid, Long userId) {

        //查询目标用户
        User targetuser = userMapper.getById(targetid);
        //账户不存在
        if (targetuser == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //判断目标用户是否为系统管理员
        if (targetuser.getIdentity() == 2) {
            throw new AccountNotAllowedException(MessageConstant.TARGET_ACCOUNT_NOT_ALLOWED_CHANGE);
        }

        //判断当前用户是否为社区管理员
        User user = userMapper.getById(userId);
        if (user.getIdentity() == 1) {
            //使用User对象，实现动态更新
            User targetUser = User.builder()
                    .status(status)
                    .id(targetid)
                    .build();
            userMapper.update(targetUser);
        }else {
            throw new AccountNotAllowedException(MessageConstant.ACCOUNT_NOT_ALLOWED);
        }
    }
}
